import React, {useContext, useEffect} from 'react';
import {View, Dimensions, Text, TouchableOpacity} from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';

import LocaleContext from '../libs/locale';
import AsyncStorage from "@react-native-async-storage/async-storage";
import {SaveMyID} from "../libs/nodes";
import WalletContext from "../libs/wallet";
import {checkAddress} from "../libs/keyPair";
import ImagePicker from "react-native-image-crop-picker";
import LocalBarcodeRecognizer from 'react-native-local-barcode-recognizer'
import {Icon} from "react-native-elements";
import Toast from "react-native-simple-toast";
import {enAES, joinGroup} from "../libs/chatGroup";

const {height,width} = Dimensions.get('window');
const ChatQRscan = ({ navigation ,route}: any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);

    const coin = route?.params?.coin || 'SAT';
    const tokenAddress = route?.params?.tokenAddress||"";

    useEffect(()=>{
        navigation.setOptions({ title: locale._("QR_Scan_Title") })
    },[])

    const onRead = ( {data} : any) => {
        console.log(`二维码数据：`+JSON.stringify(data));
        let res ;
        try{
            res = JSON.parse(data);
        }catch (e) {
            navigation.replace('Send', { receiver:data,coin, tokenAddress});
            return;
        }

        if(res.publicKey && res.address)
        {
            if(res.address == wallet.address)
            {
                Toast.show("请不要添加自己为好友")
                return;
            }
            try {
                const work = async (res: any) => {
                    let SaveList = await AsyncStorage.getItem("@chatList") || "[]";
                    let resList: any = JSON.parse(SaveList) || [];
                    for (let i = 0; i < resList.length; i++) {
                        if (resList[i].addressOut === res.address) {
                            resList[i].show = true;
                            resList[i].pubkey = res.publicKey;
                            break;
                        }
                        if (i == (resList.length - 1)) {
                            let desc = res.address.slice(0, 5) + "..." + res.address.slice(-5);//名称
                            try {
                                let NameTemp = await SaveMyID(res.address, "", "1");
                                desc = NameTemp.dict.nickname || res.address.slice(0, 5) + "..." + res.address.slice(-5);
                            } catch (e) {
                                desc = res.address.slice(0, 5) + "..." + res.address.slice(-5);
                            }
                            console.log()
                            resList.push({pubkey:res.publicKey,desc: desc, addressOut: res.address, info: []});
                            break;
                        }
                    }
                    if(resList.length == 0)
                    {
                        let desc: string;//名称
                        try {
                            let NameTemp = await SaveMyID(res.address, "", "1");
                            desc = NameTemp.dict.nickname || res.address.slice(0, 5) + "..." + res.address.slice(-5);
                        } catch (e) {
                            desc = res.address.slice(0, 5) + "..." + res.address.slice(-5);
                        }
                        resList.push({pubkey:res.publicKey,desc: desc, addressOut: res.address, info: []});
                    }
                    await AsyncStorage.setItem("@chatList", JSON.stringify(resList));
                }
                work(res).then((r) => {
                    navigation.navigate("ChatListTemp");
                });
            }catch (e) {
                navigation.goBack();
                return;
            }
            return;
        }
        else if (res.Key && res.desc && res.Creator && res.addressOut)
        {
            const joinChatGroup = async (res:any) => {
                let data = res;
                let myChatGroupList = [];
                let myChatGroupListStr = await AsyncStorage.getItem("myChatGroupList");
                if (myChatGroupListStr) {
                    myChatGroupList = JSON.parse(myChatGroupListStr);
                }
                let res_Index = myChatGroupList.findIndex((item: any) => item.addressOut === data.addressOut);
                console.log("群名称是："+JSON.stringify(data)+"\n"+data.desc)
                if (res_Index > -1) {
                    Toast.show("您已经加入该群");
                    return;
                }

                await joinGroup(wallet.address,data.Creator,data.desc,enAES(wallet.seed,data.Key),data.addressOut,data.Voucher)
                myChatGroupList.push(data);
                await AsyncStorage.setItem("myChatGroupList", JSON.stringify(myChatGroupList));
                navigation.navigate("ChatGroupView", {
                    Q_Address: data.addressOut,
                    Q_Key: data.Key,
                    QP_Priv: data.Priv,
                    Creator: data.Creator,
                    desc: data.desc
                });
            }
            joinChatGroup(res);
        }
        navigation.goBack();

    };
    const pickImg = () => {
        const handleImage = (image:any) => {
            if(image.data){
                recoginze(image.data)
            }
        }

        const recoginze = async (data:any) =>{
            let result = await LocalBarcodeRecognizer.decode(data.replace("data:image/jpeg;base64,",""),{codeTypes:['ean13','qr']});
            console.log(`result:${result}`);
            onRead({data:result});
        }


        ImagePicker.openPicker({
            width: 300,
            height: 300,
            cropping: false,
            includeBase64:true
        }).then(image => {
            handleImage(image);
        });
    }

    return (
        <>
            <Text style={{position:"absolute",width:width,top:height*0.7,color:"white",zIndex:55,textAlign:"center",fontSize:14*width/360}}>
                {locale._("QR_Scan_Tip")}
            </Text>
            <TouchableOpacity onPress={()=>{navigation.push("ChatQRcode")}}  style={{position:"absolute",left:width*0.1,top:height*0.75,zIndex:55,width:width/360*50,height:width/360*50,backgroundColor:"#DCDCDC2A",justifyContent:"center",alignItems:"center",borderRadius:width/360*50/2}}>
                <Icon type='font-awesome-5' name="qrcode" color={'white'} size={width/360*25} />
            </TouchableOpacity>

            <TouchableOpacity
                activeOpacity={0.8}
                onPress={()=>{
                        pickImg()
                    }}
                style={{position:"absolute",zIndex:55,left:78*width/100,top:75*height/100,width:width/360*50,height:width/360*50,backgroundColor:"#DCDCDC2A",justifyContent:"center",alignItems:"center",borderRadius:width/360*50/2}}>
                {/*<Text style={{fontSize:width/360*13,alignSelf:"center",textAlign:"center",padding:2,color:"white"}}>*/}
                {/*    相册*/}
                {/*</Text>*/}
                <Icon type='font-awesome-5' name="photo-video" color={'white'} size={width/360*25} />
            </TouchableOpacity>
            <View style={{flexDirection:"column",flex:1,alignItems:"center",justifyContent:"center"}}>
                {/*<View style={{ width:width*0.5,height:height*0.5 ,borderRadius:width*0.1,alignItems:"center",justifyContent:"center"}}>*/}
                <QRCodeScanner cameraStyle={{ height: '100%' }} onRead={onRead} />
                {/*</View>*/}
            </View>
        </>
    );
};

export default ChatQRscan;
